<template>
  <div v-functions="['customer_address_insert']">
    <div v-if="!noBtn">
      <el-button
        v-if="showBtn"
        icon="el-icon-plus"
        size="mini"
        style="margin-left: 10px"
        @click="openDialog({}, 'add')"
        >联系地址</el-button
      >
      <span v-else @click="openDialog({}, 'add')"
        ><i class="el-icon-plus"></i>联系地址</span
      >
    </div>
    <MoveDialog
      :visible.sync="visible"
      :before-close="closeDialog"
      class="formRef"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <span
        slot="title"
        style="color: #303753; font-size: 14px; font-weight: 600"
        >{{ title }}</span
      >
      <el-form
        ref="formRef"
        class="m7-form"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="省市区" prop="part">
          <el-cascader
            ref="cascader"
            clearable
            style="width: 100%"
            size="small"
            filterable
            v-model="formData.part"
            :options="areaList"
            :props="{ label: 'fullname', value: 'id', children: 'children' }"
            :show-all-levels="true"
            placeholder="请选择"
            @visible-change="clearChoose"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            placeholder="请填写详细地址"
            maxlength="100"
            v-model.trim="formData.detailAddress"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="是否默认"
          prop="isDefault"
          style="margin-bottom: 0px"
        >
          <el-radio-group v-model="formData.isDefault">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="mini">取 消</el-button>
        <el-button type="primary" @click="submit" size="mini">确 定</el-button>
      </div>
    </MoveDialog>
  </div>
</template>

<script lang="ts">
/**
 * 添加联系人地址按钮
 */
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { CommonModule } from '@/store/modules/common'
import { deepClone, commonAction } from '@/utils/common'
import MoveDialog from '@/components/globalTool/moveDialog/index.vue'
// 初始化数据
const defaultForm = {
  province: '',
  city: '',
  area: '',
  isDefault: 0,
  detailAddress: '',
  part: []
}
@Component({
  name: 'Address',
  components: {
    MoveDialog
  }
})
export default class Address extends Vue {
  [x: string]: any
  @Ref() private readonly formRef: any
  @Prop({ default: () => false }) private showBtn
  @Prop() private customerId
  @Prop({ default: () => false }) private noBtn
  private visible = false
  private formData = deepClone(defaultForm)
  private type = 'add'
  private title = ''
  private areaList: any = []

  private rules = {
    part: [{ required: true, trigger: 'change', message: '请选择省市区' }],
    detailAddress: [{ required: true, trigger: 'blur', message: '请填写详细地址' }],
    isDefault: [{ required: true, trigger: 'change', message: '请选择是否默认' }]
  }

  // TODO 打开对话框，可以在此填入一些数据
  private openDialog (data: any = {}, type = 'add') {
    this.type = type
    this.title = type === 'add' ? '新增联系人地址' : '编辑联系人地址'
    this.formData = type === 'add' ? deepClone(defaultForm) : deepClone(data)
    this.formData.part = type === 'add' ? [] : [data.province, data.city, data.area]
    this.visible = true
  }

  // 关闭对话框
  private closeDialog () {
    this.formRef.clearValidate()
    this.formData = deepClone(defaultForm)
    this.visible = false
  }

  private addOrUpdate () {
    const { province, city, area, detailAddress, isDefault, _id, part } = this.formData
    const sendData = {
      province: part.length && part[0],
      city: part.length && part[1],
      area: part.length && part[2],
      isDefault,
      detailAddress,
      customerId: this.customerId,
      addressId: _id
    }
    const params = { url: this.type === 'add' ? '/server-crm/action/address/add' : '/server-crm/action/address/update', method: 'POST', data: sendData }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success(`${this.type === 'add' ? '创建' : '修改'}成功`)
        this.$emit('updateAddr', res.data)
        this.closeDialog()
      }
    })
  }

  private clearChoose (val) {
    if (val) {
      this.$nextTick(() => {
        (this.$refs.cascader as any).$refs.panel.activePath = []; // 清除高亮
        (this.$refs.cascader as any).$refs.panel.syncActivePath(); // 初始化（只展示一级节点）
      })
    }
  }

  private defaultCon () {
    commonAction({
      url: '/server-crm/action/address/checkAddressDefault',
      method: 'POST',
      data: { customerId: this.customerId, addressId: this.formData._id }
    }).then(res => {
      if (res.success) {
        if (res.data) {
          this.addOrUpdate()
        } else {
          this.$confirm('检测到当前已有默认联系地址，是否进行替换为当前联系地址为默认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addOrUpdate()
          })
        }
      }
    })
  }

  // 提交
  private async submit () {
    this.formRef.validate(valid => {
      if (valid) {
        if (this.formData.isDefault) {
          this.defaultCon()
        } else {
          this.addOrUpdate()
        }
      }
    })
  }

  private mounted () {
    this.$getCache('/base/action/general/cache/query', ['region'], false).then(res => {
      if ((CommonModule as any).publicCache.region?.result.length) {
        this.areaList = (CommonModule as any).publicCache.region.result
      }
    })
  }
}
</script>
